import XLSX from 'xlsx-js-style'
import type { Ref, ComputedRef } from 'vue'
import { storeToRefs } from 'pinia'
import type {
  EnergyDataReportInformant,
} from './types'
import type { ReportList } from './useLoadList'
import { useStatementStore } from '@/store'

function withBgColor(array: any[]) {
  return array.map(v => ({
    v: v || '',
    t: 's',
    s: {
      fill: {
        fgColor: {
          rgb: 'efefef',
        },
      },
      border: {
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
        left: { style: 'thin' },
      },
    },
  }))
}

function withBorder(array: any[][]) {
  return array.map(v =>
    v.map(vv => ({
      v: vv || '',
      t: 's',
      s: {
        border: {
          top: { style: 'thin' },
          right: { style: 'thin' },
          bottom: { style: 'thin' },
          left: { style: 'thin' },
        },
      },
    })),
  )
}

export default function useReportExport(
  lists: Ref<ReportList[]>,
  informant: Ref<EnergyDataReportInformant>,
  data?: Ref<Record<string, any>>,
  summary?: ComputedRef<ReportList>,
) {
  const statementStore = useStatementStore()
  const { statementFlattenColumns: flattenColumns } = storeToRefs(statementStore)

  let isEnterpriseBasicInformationTable = false

  const getAoa = () => {
    isEnterpriseBasicInformationTable = !!(data && data.value)
    const aoa = [] as any[][]

    if (flattenColumns) {
      const headersAoa = flattenColumns.value.map(v => v.label)
      aoa.push(withBgColor(headersAoa))
    }

    if (isEnterpriseBasicInformationTable) {
      const v = data?.value || {}
      const array = [
        ['单位名称', v.tenantName, '', '', '年度', '', v.year, '', ''],
        [
          '所属地区',
          v.ssdq,
          '所属领域',
          v.ssly,
          '行业',
          '',
          v.hy,
          '单位类型',
          v.dwlx,
        ],
        [
          '单位详细名称',
          v.dwxxmc,
          '',
          '',
          '法人单位代码',
          '',
          v.frdwdm,
          '',
          '',
        ],
        [
          '单位注册日期',
          v.dwzcrq,
          '',
          '',
          '单位注册资本（万元）',
          '',
          v.dwzczb,
          '',
          '',
        ],
        [
          '法定代表人姓名',
          v.fddbrxm,
          '',
          '',
          '联系电话（区号）',
          '',
          v.lxdh,
          '',
          '',
        ],
        [
          '是否央企',
          v.sfyq,
          '',
          '',
          '所属央企集团名称',
          '',
          v.ssyqjtmc,
          '',
          '',
        ],
        ['单位地址', v.dwdz, '', '', '邮政编码', '', v.yzbm, '', ''],
        ['行政区划代码', v.xzqhdm, '', '', '电子邮箱', '', v.dzyx, '', ''],
        [
          '能源管理机构名称',
          v.nygljgmc,
          '',
          '',
          '传真（区号）',
          '',
          v.cz,
          '',
          '',
        ],
        [
          '主管节能领导姓名',
          v.zgjnldxm,
          '',
          '',
          '联系电话（区号）',
          '',
          v.lxdh1,
          '',
          '',
        ],
        [
          '能源管理负责人姓名',
          v.nyglfzrxm,
          '手机',
          v.sj,
          '能源管理师证号',
          '',
          v.nyglszh,
          '',
          '',
        ],
        [
          '是否通过能源管理体系认证',
          v.sftgnygltxrz,
          '通过日期',
          v.tgrq,
          '认证机构',
          '',
          v.rzjg,
          '',
          '',
        ],
        [
          '指标名称',
          '',
          '计量单位',
          '本期值',
          '上年值',
          '',
          '同比变化率（%）',
          '产值及能源消费变化 情况说明 ',
          '',
        ],
        ['工业总产值', '', '万元', v.bqgyzcz, v.sngyzcz, '', v.tbgyzcz, '', ''],
        ['价格指数', '', '%', v.bqjgzs, v.snjgzs, '', v.tbjgzs, '', ''],
        [
          '工业总产值(可比价)',
          '',
          '万元',
          v.bqgyzczkbj,
          v.sngyzczkbj,
          '',
          v.tbgyzczkbj,
          '',
          '',
        ],
        ['销售收入', '', '万元', v.bqxssr, v.snxssr, '', v.tbxssr, '', ''],
        ['上缴利税', '', '万元', v.bqsjls, v.snsjls, '', v.tbsjls, '', ''],
        ['从业人员', '', '人', v.bqcyry, v.sncyry, '', v.tbcyry, '', ''],
        [
          '能源管理师人数',
          '',
          '人',
          v.bqnyglsrs,
          v.snnyglsrs,
          '',
          v.tbnyglsrs,
          '',
          '',
        ],
        ['生产成本', '', '万元', v.bqsccb, v.snsccb, '', v.tbsccb, '', ''],
        [
          '能源消费成本',
          '',
          '万元',
          v.bqnyxfcb,
          v.snnyxfcb,
          '',
          v.tbnyxfcb,
          '',
          '',
        ],
        [
          '能源消费占生产成本比例',
          '',
          '%',
          v.bqnyxfzsccbbl,
          v.snnyxfzsccbbl,
          '',
          v.tbnyxfzsccbbl,
          '',
          '',
        ],
        [
          '综合能源消费量(当量值)',
          '',
          '万吨标准煤',
          v.bqzhnyxfl,
          v.snzhnyxfl,
          '',
          v.tbzhnyxfl,
          '',
          '',
        ],
        [
          '单位总产值综合能耗(当量值)',
          '',
          '吨标准煤/万元',
          v.bqdwzczzhnh,
          v.sndwzczzhnh,
          '',
          v.tbdwzczzhnh,
          '',
          '',
        ],
        ['主要产品名称', '', '年产能', '', '年产量', '', '单位产品能耗', ''],
        ['', '', '数量', '计量单位', '数量', '计量单位', '数值', '计量单位', ''],
      ]
      aoa.push(...withBorder(array))
    }

    if (lists) {
      const listsAoa = lists.value.map((v) => {
        const vv = v.data
        const item = vv.map(x => x.value || '')
        if (isEnterpriseBasicInformationTable) {
          item.splice(1, 0, '')
          item.push('')
        }
        return item
      })
      aoa.push(...withBorder(listsAoa))
    }

    if (summary) {
      const summaryAoa = summary.value.data.map(v => v.value)
      aoa.push(...withBorder([summaryAoa]))
    }

    if (informant) {
      aoa.push([])
      aoa.push([
        '填报负责人：',
        informant.value.personInCharge,
        '填报人：',
        informant.value.informer,
        '电话：',
        informant.value.telephone,
        '填报日期：',
        informant.value.fillInDate,
      ])
    }
    return aoa
  }
  const exportFile = (fileName: string, sheetName: string = 'Sheet1') => {
    const aoa = getAoa()
    // console.log('aoa: ', aoa)

    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.aoa_to_sheet(aoa)

    const cols: any[] = (ws['!cols'] = [])
    flattenColumns?.value.forEach((v, i) => {
      const length = v.label.length
      cols[i] = { wch: length * 3 }
    })

    if (isEnterpriseBasicInformationTable) {
      ws['!merges'] = [
        { s: { r: 0, c: 1 }, e: { r: 0, c: 3 } },
        { s: { r: 0, c: 4 }, e: { r: 0, c: 5 } },
        { s: { r: 0, c: 6 }, e: { r: 0, c: 8 } },
        { s: { r: 1, c: 4 }, e: { r: 1, c: 5 } },
        { s: { r: 2, c: 1 }, e: { r: 2, c: 3 } },
        { s: { r: 2, c: 4 }, e: { r: 2, c: 5 } },
        { s: { r: 2, c: 6 }, e: { r: 2, c: 8 } },
        { s: { r: 3, c: 1 }, e: { r: 3, c: 3 } },
        { s: { r: 3, c: 4 }, e: { r: 3, c: 5 } },
        { s: { r: 3, c: 6 }, e: { r: 3, c: 8 } },
        { s: { r: 4, c: 1 }, e: { r: 4, c: 3 } },
        { s: { r: 4, c: 4 }, e: { r: 4, c: 5 } },
        { s: { r: 4, c: 6 }, e: { r: 4, c: 8 } },
        { s: { r: 5, c: 1 }, e: { r: 5, c: 3 } },
        { s: { r: 5, c: 4 }, e: { r: 5, c: 5 } },
        { s: { r: 5, c: 6 }, e: { r: 5, c: 8 } },
        { s: { r: 6, c: 1 }, e: { r: 6, c: 3 } },
        { s: { r: 6, c: 4 }, e: { r: 6, c: 5 } },
        { s: { r: 6, c: 6 }, e: { r: 6, c: 8 } },
        { s: { r: 7, c: 1 }, e: { r: 7, c: 3 } },
        { s: { r: 7, c: 4 }, e: { r: 7, c: 5 } },
        { s: { r: 7, c: 6 }, e: { r: 7, c: 8 } },
        { s: { r: 8, c: 1 }, e: { r: 8, c: 3 } },
        { s: { r: 8, c: 4 }, e: { r: 8, c: 5 } },
        { s: { r: 8, c: 6 }, e: { r: 8, c: 8 } },
        { s: { r: 9, c: 1 }, e: { r: 9, c: 3 } },
        { s: { r: 9, c: 4 }, e: { r: 9, c: 5 } },
        { s: { r: 9, c: 6 }, e: { r: 9, c: 8 } },
        { s: { r: 10, c: 4 }, e: { r: 10, c: 5 } },
        { s: { r: 10, c: 6 }, e: { r: 10, c: 8 } },
        { s: { r: 11, c: 4 }, e: { r: 11, c: 5 } },
        { s: { r: 11, c: 6 }, e: { r: 11, c: 8 } },
        { s: { r: 12, c: 0 }, e: { r: 12, c: 1 } },
        { s: { r: 12, c: 4 }, e: { r: 12, c: 5 } },
        { s: { r: 12, c: 7 }, e: { r: 12, c: 8 } },
        { s: { r: 13, c: 0 }, e: { r: 13, c: 1 } },
        { s: { r: 13, c: 4 }, e: { r: 13, c: 5 } },
        { s: { r: 13, c: 7 }, e: { r: 24, c: 8 } },
        { s: { r: 14, c: 0 }, e: { r: 14, c: 1 } },
        { s: { r: 14, c: 4 }, e: { r: 14, c: 5 } },
        { s: { r: 15, c: 0 }, e: { r: 15, c: 1 } },
        { s: { r: 15, c: 4 }, e: { r: 15, c: 5 } },
        { s: { r: 16, c: 0 }, e: { r: 16, c: 1 } },
        { s: { r: 16, c: 4 }, e: { r: 16, c: 5 } },
        { s: { r: 17, c: 0 }, e: { r: 17, c: 1 } },
        { s: { r: 17, c: 4 }, e: { r: 17, c: 5 } },
        { s: { r: 18, c: 0 }, e: { r: 18, c: 1 } },
        { s: { r: 18, c: 4 }, e: { r: 18, c: 5 } },
        { s: { r: 19, c: 0 }, e: { r: 19, c: 1 } },
        { s: { r: 19, c: 4 }, e: { r: 19, c: 5 } },
        { s: { r: 20, c: 0 }, e: { r: 20, c: 1 } },
        { s: { r: 20, c: 4 }, e: { r: 20, c: 5 } },
        { s: { r: 21, c: 0 }, e: { r: 21, c: 1 } },
        { s: { r: 21, c: 4 }, e: { r: 21, c: 5 } },
        { s: { r: 22, c: 0 }, e: { r: 22, c: 1 } },
        { s: { r: 22, c: 4 }, e: { r: 22, c: 5 } },
        { s: { r: 23, c: 0 }, e: { r: 23, c: 1 } },
        { s: { r: 23, c: 4 }, e: { r: 23, c: 5 } },
        { s: { r: 24, c: 0 }, e: { r: 24, c: 1 } },
        { s: { r: 24, c: 4 }, e: { r: 24, c: 5 } },
        { s: { r: 25, c: 0 }, e: { r: 26, c: 1 } },
        { s: { r: 25, c: 2 }, e: { r: 25, c: 3 } },
        { s: { r: 25, c: 4 }, e: { r: 25, c: 5 } },
        { s: { r: 25, c: 6 }, e: { r: 25, c: 8 } },
        { s: { r: 26, c: 7 }, e: { r: 26, c: 8 } },
      ]
    }

    XLSX.utils.book_append_sheet(wb, ws, sheetName)
    XLSX.writeFile(wb, `${fileName}.xlsx`)
  }

  return {
    exportFile,
  }
}
